import * as qiniu from "qiniu-js";
import { getQiNiuToken } from "./external";
import type { VNodeChild } from "vue";
import { v1 as uuidv1 } from 'uuid';
export const upload = async (file: FormData) => {
  //开始请求
  const res = await useServerRequest<{ url: string }>("/file/upload", {
    method: "POST",
    body: file,
  });
  return res?.data;
};
export const uploadPostCoverUrl = async (file: FormData) => {
  //开始请求
  return await useServerRequest<{ url: string }>("/file/uploadPostCoverUrl", {
    method: "POST",
    body: file,
  });
};
export const deleteFile = async (fileNos: any[]) => {
  const res = await useServerRequest<{ url: string }>("/file/upload", {
    method: "POST",
    body: {
      fileNos,
    },
  });
  return res?.data;
};

/**
 * 七牛上传
 * */
export async function qiniuUpload(file: File, isCv = false) {
  const token = await getQiNiuToken();
  if (!token) return;
  let prefix = "blog/";
  // 证明是粘贴,添加时间戳
  if (isCv) {
    prefix += Date.now() + ".";
  }
  const observable = qiniu.upload(file, prefix + uuidv1(), token);
  const messageReactive = naiveui.message.loading("上传中Verifying", {
    duration: 0,
  });
  return new Promise((resolve, reject) => {
    const observer: any = {
      next({ total }: { total: any }) {
        const { percent } = total;
        if (percent >= 100 && messageReactive) {
          messageReactive.destroy();
        }
      },
      error(err: string | (() => VNodeChild)) {
        naiveui.message.error(err);
        messageReactive.destroy();
        reject(err);
      },
      complete(res: { hash: string; url: string }) {
        naiveui.message.success("上传成功");
        messageReactive.destroy();
        resolve(res);
      },
    };
    observable.subscribe(observer);
  });
}
